<?php
namespace app\admin\controller;

use app\admin\Controller;
use think\Db;
/**
 * 公共上传控制器类
 * 继承了图片，文件上传方法 包括一些业务逻辑的处理
 * 图片上传本地，七牛云，execl上传试题等
 */
class Upload extends Controller
{
    /**
     * 首页
     */
    public function index()
    {
        return $this->view->fetch();
    }

    public function uploadLocal()
    {
        return $this->view->fetch();
    }
	
	 public function addlocal()
    {
        return $this->view->fetch();
    }

    public function file()
    {
        return $this->view->fetch();
    }
	public function fileimg()
    {
        return $this->view->fetch();
    }
    /**
     * excel上传
     */
    public function excel()
    {
        $qbankid = $this->request->param('qbankid');
        $child_plaform = getChildAdminRegByPlaformId($this->plaform);
        $knows = Db::name('Knows')->where(['admin_reg'=>['in',$child_plaform]])->select();
//        $Type  = Db::name('questype')
////            ->where('admin_reg',$_SESSION['think']['reg'])
//            ->select();
//
        $knows = setArrKeyId($knows);
        $this->view->assign('qbankid',$qbankid);
//        $this->view->assign('Type',$Type);
        $this->view->assign('knows',$knows);
        if(cookie('dataPoint')){
            $this->view->assign('dataPoint',cookie('dataPoint'));
            $this->view->assign('sectionid',cookie('sectionid'));
            $this->view->assign('subjectid',cookie('subjectid'));
        } else {
            $this->view->assign('dataPoint',0);
        }
        //查询知识点
        
        return $this->view->fetch();
    }
    /**
     * 文件上传
     */
    public function upload()
    {
        $file = $this->request->file('file');
        $path = ROOT_PATH . 'public/tmp/uploads/';
        $info = $file->move($path);
        if (!$info) {
            return ajax_return_error($file->getError());
        }
        $data = $this->request->root() . '/tmp/uploads/' . $info->getSaveName();
        $insert = [
            'cate'     => 3,
            'name'     => $data,
            'original' => $info->getInfo('name'),
            'domain'   => '',
            'type'     => $info->getInfo('type'),
            'size'     => $info->getInfo('size'),
            'mtime'    => time(),
        ];
        Db::name('File')->insert($insert);

        return ajax_return(['name' => $data]);
    }

    /**
     * 文件上传
     */
    public function uploadexcel()
    {
        $_answer = null;
        $_answerData = NULL;
        $file = $this->request->file('file');
        $fileinfo = $file->getInfo();
        $path = ROOT_PATH . 'public/tmp/uploads/';
        $info = $file->move($path, $fileinfo['name']);
        $url = './tmp/uploads/' . $info->getSaveName();

        // 通过文件上传，然后取到上传后的完整路径文件名
//        $file;
        // 解析 Excel 头部信息，返回 $excelHeader = ['A' => '第一行A列描述', 'B' => '第一行B列描述', 'C' => '第一行C列描述',...]
        $excelHeader = \Excel::parseHeader($url);
//        var_dump($excelHeader);die;
        // 将 $excelHeader 数据抛给前端，让用户选择对应关系，然后再返回给后台进行对应数据的解析，例如抛给后台的数据如下isdelete selectnumber describe status level answer
        $header = ['A' => 'q_typeid', 'B' => 'q_question', 'C' => 'q_select', 'D' => 'q_selectnumber', 'E' => 'q_answer', 'F' => 'q_describe'];
        $result = \Excel::parse($url, $header, 20, function ($data) {
                    
                    /**
                     * 可以在此处对数据进行过滤处理，例如：
                     */
                    foreach ($data as &$v) {
                        $_select = \app\common\logic\DrawQuestion::exAnswerStrToArr($v['q_select']);
                        $v['q_answer'] = str_replace(',', '', $v['q_answer']);
                        $v['q_status'] = 1;
                        $v['q_level'] = 1;
                        $v['admin_reg'] = $_SESSION['think']['reg'];
                        $v['q_qbankid'] = $this->request->param('qbankid');
                        $v['q_create_time'] = time();
                        $v['q_knowsid'] = $this->request->param('datapoint');
                        $v['q_subjectid'] = $this->request->param('subjectid');
                        $v['q_sectionid'] = $this->request->param('sectionid');

						$answerFormat = '';
                        foreach ($_select as $kw => $aw) {
                            $_answerData[] = array(
                                'questions_id' => $qid,
                                'option' => $kw ? $kw : 'UNKOWN',
                                'answer' => $aw ? $aw : 'UNKOWN'
                            );
							//处理答案选项为标准格式
							$answerFormat .= $kw < count($_select) ? $kw.'.'.trim($aw).' ' : $kw.'.'.trim($aw);														
                        }
						$v['q_select'] = $answerFormat;		
						$qid = Db::name('questions')->insert($v, FALSE, TRUE);			
                    }
                    Db::name('QuestionsAnswer')->insertAll($_answerData);
//            $cache = new Cache();
//            $cache->set('shiti',$data,3600);//存缓存
                });
        $child_plaform = getChildAdminRegByPlaformId($this->plaform);
        $questions = new \app\common\model\Questions();
        $ques = Db::table($questions->tablename())->where(['admin_reg'=>['in',$child_plaform], 'q_status' => 1, 'isdelete' => 0])->field('count(*) as num')->find();
        if (empty($ques['num']))
            $ques['num'] = 0;
        $qbank = new \app\common\model\Qbank();
        Db::table($qbank->tablename())->where('id', $this->request->param('qbankid'))->update(['total' => $ques['num']]);

        $insert = [
            'cate' => 3,
            'name' => $url,
            'original' => $info->getInfo('name'),
            'domain' => '',
            'type' => $info->getInfo('type'),
            'size' => $info->getInfo('size'),
            'mtime' => time(),
        ];
        Db::name('File')->insert($insert);

        return ajax_return(['name' => $url]);
    }
	
	/****uploadexcel 步骤分为2步操作***/
	 public function uploadexcel1()
    {
        $_answer = null;
        $_answerData = NULL;
        $file = $this->request->file('file');
        $fileinfo = $file->getInfo();
        $path = ROOT_PATH . 'public/tmp/uploads/';
        $info = $file->move($path, $fileinfo['name']);
        $url = './tmp/uploads/' . $info->getSaveName();
		return ajax_return(['name' => $url]);
	}
	

	/**
     * 顶级题库试题导入
     * 
     */
	 public function uploadexcel2()
    {

        $url = $this->request->param('url');

		if(!$url){
			return '没有上传文件';
		}

        // 通过文件上传，然后取到上传后的完整路径文件名
        // $file;
        // 解析 Excel 头部信息，返回 $excelHeader = ['A' => '第一行A列描述', 'B' => '第一行B列描述', 'C' => '第一行C列描述',...]
		
        $excelHeader = \Excel::parseHeader($url);

        // 将 $excelHeader 数据抛给前端，让用户选择对应关系，然后再返回给后台进行对应数据的解析，例如抛给后台的数据如下isdelete selectnumber describe status level answer
        $header = ['A' => 'q_typeid', 'B' => 'q_question', 'C' => 'q_select', 'D' => 'q_selectnumber', 'E' => 'q_answer', 'F' => 'q_describe'];

         $result = \Excel::parse($url, $header, 20, function ($data) { 
                    /**
                     * 可以在此处对数据进行过滤处理，例如：
                     */
                    foreach ($data as &$v) { 
                        if ($v['q_question']=='' || $v['q_typeid']==''){
                            continue;
                        }
                        if ($v['q_describe']=='')$v['q_describe'] = ' ';
                        $_select = \app\common\logic\DrawQuestion::exAnswerStrToArr($v['q_select']);
                        if ($v['q_typeid']==3 && empty($v['q_select'])) {
                        	$v['q_select'] = 'A.正确 B.错误';
                        }
                        
                        
                        
                        $v['q_answer'] = trim(str_replace(',', '', $v['q_answer']));
                        var_dump($v['q_answer']);
                        $v['q_status'] = 1;
                        $v['q_level'] = 1;
                        $v['admin_reg'] = $_SESSION['think']['reg'];
                        $v['q_qbankid'] = $this->request->param('qbankid');
                        $v['q_create_time'] = time();
                        $v['q_knowsid'] = "0";$this->request->param('datapoint'); //知识点id
                        $v['q_subjectid'] = "1";$this->request->param('subjectid'); //科目id
                        $v['q_sectionid'] = "1";$this->request->param('sectionid'); //章节id

						$answerFormat = '';
                        foreach ($_select as $kw => $aw) {
                            
                            # 新增图片类型试题
                            if($v['q_typeid']==12){
                                $tmp_url = $this->imageQuestionsRemote($aw);

                                $url =$this->imageQuestionsUpload();   
                                $_answerData[] = array(
                                    'questions_id' => $qid,
                                    'option' => $kw ? $kw : 'UNKOWN',
                                    'answer' => $url ? $url : 'UNKOWN'
                                );
                            }else{
                                $_answerData[] = array(
                                    'questions_id' => $qid,
                                    'option' => $kw ? $kw : 'UNKOWN',
                                    'answer' => $aw ? $aw : 'UNKOWN'
                                );    
                            }
							//处理答案选项为标准格式
							$answerFormat .= $kw < count($_select) ? $kw.'.'.trim($url).' ' : $kw.'.'.trim($url);														
                        }

						$v['q_select'] = $answerFormat;
						$qid = Db::name('questions')->insert($v, FALSE, TRUE);
                    }
                    Db::name('QuestionsAnswer')->insertAll($_answerData); 
                });exit;

        $child_plaform = getChildAdminRegByPlaformId($this->plaform);
        $questions = new \app\common\model\Questions();
        // 'admin_reg'=>['in',$child_plaform], # reg权限码去除 加入q_qbankid
        $ques = Db::table('agk_questions')->where(['admin_reg'=>['in',$child_plaform],'q_status' => 1, 'isdelete' => 0,'q_qbankid'=>$this->request->param('qbankid')])->field('count(*) as num')->find();
        if (empty($ques['num']))
            $ques['num'] = 0; 
        // var_dump($ques);exit;
        Db::table('agk_qbank')->where('id', $this->request->param('qbankid'))->update(['total' => $ques['num']]);

        return '操作完成';
    }
	
	
	/****uploadexcel 步骤分为2步操作 end***/
	

    /**
     * 文件上传
     */
    public function uploadfile()
    {

        $result = \Qiniu::instance()->upload();//七牛上传
        $url=config("qiniu.QINIU_DOMAIN").$result[0]['key'];

//        $file = $this->request->file('file');
//        $fileinfo=$file->getInfo();
//        $path = ROOT_PATH . 'public\tmp\uploads\\';
//        var_dump($fileinfo['name']);die;
//        $info = $file->move($path,$fileinfo['name']);
//
//        $url = './tmp/uploads/' . $info->getSaveName();
        $insert = [
            'cate'     => 3,
            'name'     => $url,
            'original' => $result[0]['name'],
            'domain'   => '',
            'type'     => $result[0]['type'],
            'size'     => $result[0]['size'],
            'mtime'    => time(),
        ];
       $id= Db::name('File')->insert($insert,false,true);

        return ajax_return(['name' => $url,'original' => $result[0]['name'],'id'=>$id]);
    }
    /**
     * 远程图片抓取
     */
    public function remote()
    {
        $url = $this->request->post('url');
        // validate
        $name = ROOT_PATH . 'public/tmp/uploads/' . get_random();
        $name = \File::downloadImage($url, $name);

        $ret = $this->request->root() . '/tmp/uploads/' . basename($name);

        return ajax_return(['url' => $ret], '抓取成功');
    }
    /**
     * 图片列表
     */
    public function listImage()
    {
        $page = $this->request->param('p', 1);
        if ($this->request->param('count')) {
            $ret['count'] = Db::name('File')->where('cate=3')->count();
        }
        $ret['list'] = Db::name('File')->where('cate=3')->field('id,name,original')->page($page, 10)->select();
        return ajax_return($ret);
    }
    /**
     * 图片试题图片上传
     */
	public function imageQuestionsUpload()
    {
         $result = \Qiniu::instance()->upload();//七牛上传
        $url=config("qiniu.QINIU_DOMAIN").$result[0]['key']; 
        $insert = [
            'cate'     => 3,
            'name'     => $url,
            'original' => $result[0]['name'],
            'domain'   => '',
            'type'     => $result[0]['type'],
            'size'     => $result[0]['size'],
            'mtime'    => time(),
        ];
        //     'name'     => $url."?imageView2/1/h/100/w/100", # 获取压缩图片
       // $id= Db::name('File')->insert($insert,false,true);

        return $url?$url:"空";
    }
    /**
     * 远程图片抓取
     */
    public function imageQuestionsRemote($url = "")
    {
        if(empty($url)){
            return '没有图片上传';
        }
        // validate
        $name = ROOT_PATH . 'public/tmp/uploads/' . get_random();
        $name = \File::downloadImage($url, $name);

        $ret = $this->request->root() . '/tmp/uploads/' . basename($name);

        return $ret;
    }
	

}